<!--  -->
<template>
  <div class="map-body">
    <div class="left-container">
      <div class="myecharts">
        <div :style="{ height: '100%', width: '100%' }" ref="myEchart"></div>
      </div>
    </div>
  </div>
</template>
<script>
  import echarts from 'echarts';
  import Api from '../../../api/assetsMap';
  import cityMap from '../../../config/cityMap';
  import provinceMap from '../../../config/provinceMap';
  import { getMenuList } from '@/api';
  export default {
    props:{
      projectData:{
        type: Array,
        default:()=>{
          return []
        }
      },
      projectKey:{
        type: String,
        default: ''
      }
    },
    components: {},
    data() {
      return {
        activeIndex: 1,
        echartOption: {
          animationDuration: 700,
          animationEasing: 'cubicOut',
          animationDurationUpdate: 700,
          tooltip: {},
          // 地图样式
          geo: {
            layoutSize: '120%', //地图大小
            layoutCenter: ['50%', '50%'], //0-横向偏移量 1-竖向偏移量
            scaleLimit: {
              min: 1,
              max: 20,
            },
            map: 'china',
            zoom: 1,
            roam: false,

            left: 0,
            right: 0,
            label: {
              sohw: true,
              normal: {
                show: true,
                textStyle: {
                  color: '#999',
                },
              },
              emphasis: {
                color: '#F79100',
              },
            },
            itemStyle: {
              normal: {
                areaColor: '#f1f1f1',
                borderColor: '#fff',
              },
              emphasis: {
                areaColor: '#f0f0f0',
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowBlur: 20,
                borderWidth: 0,
                shadowColor: 'rgba(0, 0, 0, 0.1)',
              },
            },
            regions: [],
          },

          series: [
            {
              type: 'effectScatter',
              legendHoverLink: true,
              effectType: 'ripple',
              showEffectOn: 'emphasis',
              coordinateSystem: 'geo',
              data: [],
              symbol: 'circle',
              symbolSize: 15,
              rippleEffect: {
                period: 4,
                scale: 2.5,
                brushType: 'stroke',
              },
              itemStyle: {
                color: '#F79100',
              },
              tooltip: {
                show: true,
                trigger: 'item',
                showContent: true,
                showDelay: 0,
                hideDelay: 100,
                enterable: true,
                renderMode: '',
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.8)',
                },
                backgroundColor: 'rgba(0, 0, 0, 0.1)',
                formatter: '{b}',
              },
            },
            {
              type: 'effectScatter',
              legendHoverLink: true,
              effectType: 'ripple',
              showEffectOn: 'render',
              coordinateSystem: 'geo',
              animation: false,
              data: [],
              symbol: 'circle',
              symbolSize: 15,
              rippleEffect: {
                period: 4,
                scale: 2.5,
                brushType: 'stroke',
              },
              itemStyle: {
                color: '#F79100',
              },
              tooltip: {
                show: true,
                trigger: 'item',
                showContent: true,
                showDelay: 0,
                hideDelay: 100,
                enterable: true,
                renderMode: '',
                textStyle: {
                  color: 'rgba(0, 0, 0, 0.8)',
                },
                backgroundColor: 'rgba(0, 0, 0, 0.1)',
                formatter: '{b}',
              },
            },
          ],
        },
        myChart: null,
        mapPath: ['china'],
        allData: [],
        basicData: null,
        serviceData: null,
        equipmentData: null,
        levelList: ['china', 'province', 'city'],
        nowLevel: 'china',
        areaColors: ['#0d50d6', '#0841af', '#2281cf'],
        zoom: 1,
        Route: {},
      };
    },
    watch: {
      Route: {
        immediate: false,
        deep: true,
        handler(val) {
          this.goArea();
        },
      },
      projectData: {
        immediate: true,
        deep: true,
        handler(val) {
          this.$nextTick(() => {
            this.projectList();
          })
        },
      },
      projectKey: {
        immediate: true,
        deep: true,
        handler(val) {
          this.resetData();
        },
      },
    },
    destroyed() {
      if (this.dataTimer) {
        clearTimeout(this.dataTimer);
      }
    },
    filters: {
      thousandth(value) {
        return Number(value)
          .toFixed(2)
          .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
      },
      thousandthInteger(value) {
        var reg = /\d{1,3}(?=(\d{3})+$)/g;
        return (value + '').replace(reg, '$&,');
      },
    },
    methods: {
      async projectList() {
        // let provinceCodeList = [];
        this.projectData.forEach(item => {
          // provinceCodeList.push(item.provinceCode);
          this.allData.push({
            mapName: item.provinceName,
            name: item.name,
            value: [Number(item.longitude), Number(item.latitude)],
            code: item.primaryKey,
            spaceKey: item.spaceKey,
          });
        });
        // let repetArr = [...new Set(provinceCodeList)];
        // if (repetArr.length == 1) {
        //   this.Route = { cityName:  rows[0].provinceName};
        // }
        this.drawECharts();
      },
      async drawECharts() {
        this.myChart = echarts.init(this.$refs.myEchart);
        window.onresize = this.myChart.resize;

        this.goArea();

        this.myChart.on('click', params => {
          this.clickHandel(params);
        });
      },
      setRouter() {
        if (this.mapPath.length == 1) {
          this.Route = {};
        } else {
          this.Route = { cityName: this.mapPath.slice(1).join(',') };
        }
      },
      async clickHandel(params) {
        // if (params.name in provinceMap) {
        //   // 更新路径
        //   this.mapPath.push(params.name);
        //   // 如果点击的是34个省、市、自治区，绘制选中地区的二级地图
        //   this.setRouter();
        // } else if (params.name in cityMap) {
        //   // 更新路径
        //   this.mapPath.push(params.name);

        //   this.setRouter();
        // } else 

        if (params.componentSubType == 'effectScatter') {
          // if (!params.data.type) {
          //   this.mapPath.push(params.data.mapName);
          //   // 如果点击的是34个省、市、自治区，绘制选中地区的二级地图
          //   this.setRouter();
          //   return;
          // }

          this.handleView({
            projectKey: params.data.code,
            spaceKey: params.data.spaceKey,
          });
        }
      },
      async handleView(data) {
        let res = await getMenuList({
          parentId: this.$route.query.menuId,
        });

        let menuUrl = res.rows[0].menuUrl;
        let separator = menuUrl.indexOf('?') > -1 ? '&' : '?';
        let queryData = {
          ...data,
          isRefresh: true,
          parentMenuId: this.$route.query.menuId,
          menuId: res.rows[0].primaryKey,
          noTab: true,
        };

        let paramData = [];
        for (let key in queryData) {
          paramData.push(key + '=' + queryData[key]);
        }

        let href = menuUrl + separator + paramData.join('&');
        // console.log(href, 'href')
        window.open(href);
      },
      async goToArea(type = 'china', name = 'china') {
        let data = null;
        if (type == 'province') {
          data = await Api.getProvinceMapJson({ jsonName: provinceMap[name] });
          this.nowLevel = 'province';
        } else if (type == 'city') {
          data = await Api.getCityMapJson({ jsonName: cityMap[name] });
          this.nowLevel = 'city';
        } else {
          data = await Api.getChinaMapJson();
          this.nowLevel = 'china';
        }

        await this.getData();

        let regions = [];

        echarts.registerMap(name, data);
        this.echartOption.geo.map = name;
        this.echartOption.geo.regions = regions;
        this.echartOption.geo.center = null;
        this.echartOption.geo.zoom = 1;

        this.myChart.setOption(this.echartOption, true);
      },
      async resetData () {
        await this.getData();
        this.myChart.setOption(this.echartOption, true);
      },
      async getData() {
        let name = this.mapPath[this.mapPath.length - 1];
        if (this.nowLevel == 'province') {
          await this.getSpotList('province', name);
        } else if (this.nowLevel == 'city') {
          await this.getSpotList('city', name);
        } else {
          await this.getSpotList();
        }

        // 清除之前的轮询，重新轮询
        // if (this.dataTimer) {
        //   clearTimeout(this.dataTimer);
        // }

        // this.dataTimer = setTimeout(() => {
        //   this.getData();
        // }, 180000);
      },
      async getSpotList(type = '', name = '') {
        this.allData.forEach(item => {
          item.type = type;
        });

        let data = []
        let nowData = []

        if (!type) {
          data = this.allData;
        } else if (type == 'province') {
          data = this.allData.filter(item => {
            return item.mapName == name;
          });
        }

        nowData = data.filter(item => {
          return item.code == this.projectKey;
        })

        this.echartOption.series[0].data = data;
        this.echartOption.series[1].data = nowData;
      },
      goArea() {
        if (this.Route.cityName) {
          let nameList = this.Route.cityName.split(',');
          let length = nameList.length;
          let cityName = nameList[length - 1];

          this.mapPath = ['china'].concat(nameList);

          if (cityName in provinceMap) {
            this.goToArea('province', cityName);
          } else if (cityName in cityMap) {
            this.goToArea('city', cityName);
          }
        } else {
          this.mapPath = ['china'];

          this.goToArea();
        }
      },
      async goBack() {
        this.mapPath.pop();
        this.setRouter();
      },
      zoomBtn(type) {
        if (type == 'minus' && this.echartOption.geo.zoom == 1) {
          return;
        }

        if (type == 'add' && this.echartOption.geo.zoom == 20) {
          return;
        }

        if (type == 'minus') {
          this.echartOption.geo.zoom = Math.max(1, this.echartOption.geo.zoom - 2);
        } else if (type == 'add') {
          this.echartOption.geo.zoom = Math.min(20, this.echartOption.geo.zoom + 2);
        }

        if (this.echartOption.geo.zoom == 1) {
          this.echartOption.geo.center = null;
        }

        this.myChart.setOption(this.echartOption, true);
      },
    },
  };
</script>
<style scoped lang="scss">
  .myecharts {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .map-body {
    height: 100%;
    width: 100%;

    .left-container {
      flex: 1;
      height: 100%;
      position: relative;
    }
  }
</style>
